<template lang="html">
  <div class="view-book-content-empty" v-if="!hasBook">
    <el-empty :description="emptyMsg" />
  </div>
  <div class="view-book-content-main" v-else>
    <!-- <div class="view-book-content-bookInfo">
      <p class="view-book-content-bookTitle">
        <span class="view-book-content-icon" />
        <el-image :src="currentBook.bookPic" class="view-book-content-img" :lazy="true" />
        <span class="view-book-content-bookName">{{ currentBook.bookName }}</span>
        <span>{{ currentBook.bookAuthor }}</span>
      </p>
      <p class="view-book-content-desc">{{ currentBook.bookDesc }}</p>
    </div> -->
    <div class="view-book-content-reader" v-loading="contentLoading">
      <div class="view-book-content-left">
        <div class="view-book-content-toolbar">

          <div class="btn-toolbar" v-if="prevChapter" @click="choseChapter(prevChapter)">
            <span class="book-svg-icon">
              <span>上一章</span>
            </span>
          </div>

          <div class="btn-toolbar" @click="bookChapterRef.openDrawer()">
            <span class="book-svg-icon">
              <span>目录</span>
            </span>
          </div>

          <div class="btn-toolbar" v-if="nextChapter" @click="choseChapter(nextChapter)">
            <span class="book-svg-icon">
              <span>下一章</span>
            </span>
          </div>
        </div>
      </div>
      <div class="view-book-content-bookContent book-scroll" :id="`book-content-${bookId}`">
        <el-affix target=".view-book-content-main" :offset="0" class="chapter-affix">
          <div class="chapter-title">
            <span>{{ currentChapter.volumeName }}</span><span>{{ currentChapter.name }}</span>
          </div>
        </el-affix>
        <p v-for="content in currentContents" :index="content.seq" :data-wordsNumber="content.wordsNumber">
          {{ '&nbsp;&nbsp;&nbsp;&nbsp;' + content.content }}
        </p>
      </div>
      <div class="view-book-content-right"></div>
    </div>
  </div>

  <BookChapterDrawer ref="bookChapterRef" :book-chapters="bookChapters" :current-chapter="currentChapter" />
</template>
<script setup>
import { onMounted, provide, ref } from 'vue';
import { ElMessage } from 'element-plus'
import BookChapterDrawer from './components/BookChapterDrawer.vue';
import { useBookshelfStore } from '@/stores/bookshelf';
import { useBookContentStore } from '@/stores/bookContent';
import { useBookChapterStore } from '@/stores/bookChapter';
import { useRouter } from 'vue-router'
const bookshelfStore = useBookshelfStore();
const bookContentStore = useBookContentStore();
const bookChapterStore = useBookChapterStore();
const router = useRouter();

const props = defineProps({
  bookId: {
    type: String,
    default: '',
  },
  chapterId: {
    type: String,
    default: '',
  },
});

const emptyMsg = ref('请选择书籍');
const hasBook = ref(false);
const currentContents = ref([]);
const currentChapter = ref(null); // 获取当前章节
const bookChapterRef = ref({});
const bookChapters = ref([]); // 书籍章节目录
const contentLoading = ref(false); // 内容加载中
const prevChapter = ref(null); // 上一章
const nextChapter = ref(null); // 下一章

function initBookContent() {
  hasBook.value = false; // 设置书籍不存在
  currentContents.value = []; // 设置当前内容
  currentChapter.value = null; // 设置当前章节
  bookChapters.value = []; // 设置章节目录
  contentLoading.value = false; // 设置加载完成
  prevChapter.value = null // 上一章
  nextChapter.value = null // 下一章
}
// 展示内容
function showContent(contents) {
  bookshelfStore.updateBookLastReadingCharpter(props.bookId, props.chapterId); // 更新书籍最后阅读章节
  console.log('book-content', contents);
  if (contents.length == 0) {
    emptyMsg.value = '书籍内容不存在';
    return Promise.reject('书籍内容不存在');
  }
  hasBook.value = true; // 设置书籍存在
  currentContents.value = contents;
  calcPrveAndNextChapter(); // 计算上一章和下一章
  return Promise.resolve(contents);
}

// 滚动到顶部
function scrollToChapter() {
  const bookContent = document.getElementById(`book-content-${props.bookId}`);
  bookContent.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}

function calcPrveAndNextChapter() {
  const currentChapterId = currentChapter.value.id;
  const chapters = bookChapters.value;
  const currentIndex = chapters.findIndex((item) => {
    return item.id == currentChapterId;
  });
  if (currentIndex > 0) {
    prevChapter.value = chapters[currentIndex - 1];
  } else {
    prevChapter.value = null;
  }
  if (currentIndex < chapters.length - 1) {
    nextChapter.value = chapters[currentIndex + 1];
  } else {
    nextChapter.value = null;
  }
}


// 校验书籍章节
function checkProps() {
  return new Promise(async (resolve, reject) => {
    if (!props.bookId || !props.chapterId) {
      reject('缺少书籍ID或章节ID');
      return;
    }
    resolve();
  });
}

function loadBookContent() {
  contentLoading.value = true; // 设置加载中
  return checkProps()
    .then(() => {
      return bookChapterStore.getBookChapters(props.bookId);
    }).then((chapters) => {
      bookChapters.value = chapters; // 设置章节目录
      return bookChapterStore.getBookChapter(props.bookId, props.chapterId)
    })
    .then((chapter) => {
      currentChapter.value = chapter; // 设置当前章节
      calcPrveAndNextChapter();
      return bookContentStore.loadContent(props.bookId, chapter);
    })
    .then((contents) => {
      return showContent(contents);
    })
    .catch((err) => {
      console.error('book-content', err);
      ElMessage({
        message: err,
        type: 'error',
      });
    }).finally(() => {
      contentLoading.value = false; // 设置加载完成
      scrollToChapter(); // 滚动到当前章节
    });
}

onMounted(() => {
  initBookContent(); // 初始化状态
  loadBookContent(); // 加载书籍内容
});


// 选择章节
function choseChapter(chapter) {
  router.push({
    path: `/content/${props.bookId}/${chapter.id}`
  });

  initBookContent(); // 初始化状态
  loadBookContent(); // 加载书籍内容
}

provide("bookContentEvent", {
  choseChapter
})

</script>
<style lang="less" scoped>
.view-book-content-empty {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.view-book-content-main {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 1px;
  overflow: hidden;


  .view-book-content-bookInfo {
    padding-bottom: 10px;
    border-bottom: 1px solid #eaeaea;

    .view-book-content-bookTitle {
      height: 40px;
      line-height: 40px;
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .view-book-content-icon {
        display: inline-block;
        height: 40px;
        width: 5px;
        background-color: #0080ff;
        margin-right: 10px;
      }

      .view-book-content-img {
        width: 40px;
        height: 50px;
        display: flex;
        border-radius: 5px;
        margin-right: 10px;
      }


      .view-book-content-bookName {
        font-size: 22px;
        font-weight: bold;
        margin-right: 10px;
      }
    }

    .view-book-content-desc {
      font-size: 14px;
    }
  }

  .view-book-content-reader {
    display: flex;
    flex: 1;
    height: 0px;
    overflow: hidden;

    .view-book-content-left {
      flex: 1;
      flex-grow: 1;
      width: 20%;
      position: relative;

      .view-book-content-toolbar {
        position: absolute;
        width: 80px;
        height: 200px;
        bottom: 100px;
        right: 0px;
        display: flex;
        flex-direction: column;

        .btn-toolbar {
          width: 80px;
          height: 80px;
          border-radius: 5px;
          background-color: #f1f1f1;
          margin-bottom: 10px;

          .book-svg-icon {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            width: 100%;
            cursor: pointer;

            .book-icon:hover {
              color: #8888f2 !important;
            }

            .book-icon svg:hover path {
              color: #8888f2 !important;
            }
          }

        }


      }
    }

    .view-book-content-bookContent {
      padding: 10px;
      flex: 1;
      flex-grow: 3;
      overflow: hidden;
      overflow-y: scroll;
      border: 1px solid #eaeaea;
      border-top: none;
      border-bottom: none;
      font-size: 16px;

      .chapter-title {
        font-size: 22px;
        color: #000;
        margin-bottom: 20px;
        height: 60px;
        line-height: 60px;
        background-color: #fff;

        span {
          display: inline-block;
          margin-left: 20px;
        }
      }

      p {
        margin: 10px 0px;
        font-size: 16px;
      }

      p:last-child {
        padding-bottom: 50px;
      }

    }

    .view-book-content-right {
      flex: 1;
      flex-grow: 1;
      width: 20%;
    }
  }

}
</style>
